package _interview150;

import java.util.ArrayList;
import java.util.List;

/**
 * 22. 括号生成
 */
public class No22 {
    private List<String> ans;
    private char[] path;
    private int n;

    public List<String> generateParenthesis(int n) {
        ans = new ArrayList<>();
        path = new char[n * 2];
        this.n = n;
        dfs(0, 0, 0);
        return ans;
    }

    private void dfs(int i, int l, int r) {
        if (l < r || l > n) return;
        if (i == 2 * n) {
            ans.add(new String(path));
            return;
        }

        path[i] = '(';
        dfs(i + 1, l + 1, r);

        path[i] = ')';
        dfs(i + 1, l, r + 1);
    }
}
